package com.lanhai.longheng;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake; 

public class WebSocketCore {
	private static WebSocketClient wsClient=null;

	 private static final Logger logger = LogManager.getLogger("agvlog");
	private String ip;
	boolean running=false;
	Thread th;
	
	static  Map<Integer,String> sendMap=Collections.synchronizedMap(new HashMap<Integer,String>());
	
	
	
	public WebSocketCore(String ip) { 
		this.ip=ip; 
	}
	
	public void Start() {
		running=true;
		th=new Thread() { 
			@Override
			public void run() {
				 while(running) {
					 connect();
					 try {
						Thread.sleep(10000);
					} catch (InterruptedException e) {
						 
					}
				 }
			}
			
		};
		th.start();
	}
	
	
	void connect() {
		if(wsClient!=null&&wsClient.isClosed()==false) {
			return;
		}
		 
		try { 
			String url = "ws://" + ip + ":8012/echo/username=sys&src=svr";
			wsClient = new WebSocketClient(new URI(url), new Draft_6455()) {
				@Override
				public void onOpen(ServerHandshake serverHandshake) {
					logger.info("websocket 握手成功！");
				}

				@Override
				public void onMessage(String msg) {
					logger.info("websocket 收到消息==========" + msg);
					if (msg.equals("over")) {
						wsClient.close();
						wsClient=null;
					}
				}

				@Override
				public void onClose(int i, String s, boolean b) {
					logger.info("websocket 链接已关闭");
					wsClient = null;
				}

				@Override
				public void onError(Exception e) { 
					logger.info("websocket 发生错误已关闭");
					wsClient = null;
				}
			};
		} catch (URISyntaxException e) {
			wsClient=null;
		}
		try {
			if(wsClient!=null) {
				wsClient.connect();
			}
		}catch(Exception e) {
			wsClient=null;
		}
	}
	
	public static synchronized void sendMsgByWs_back(int agvid, String msg) {
		if (wsClient == null) {
			//logger.error(String.format( "没有websocket连接，无法向AGV【%d】发送消息：【%s】",agvid,msg));
		} else {
			if(wsClient.isClosed()==false) {
				//相同指令不用发
				 
				String tp=sendMap.get(agvid);
				if(tp!=null&&tp.equals(msg)) {
					return;
				}
				 
				
				sendMap.put(agvid, msg);
				String msgp = "{receiver:'no" + agvid + "_agv',data:'" + msg + "'}"; 
				try {
				wsClient.send(msgp);
				}catch(Exception ex) {}
			}else {
				logger.error("websocket非空，但没有连接" );
			}
		
		}
	}

	public void Stop() {
		running=false;
		try {
			if(th!=null) {
				th.interrupt();
				th=null;
			}
		}catch(Exception e) {
			
		}
		if(wsClient!=null) {
			wsClient.close();
			wsClient = null;
		} 
	}
}
